import type { CaseReducer, PayloadAction } from '@reduxjs/toolkit';
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { commonDataApi } from '@/api';

type commonDataType = {
  industryList: any[];
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error: string | null;
  tradeMap: Map<string, string>;
};

export const getIndustryList = createAsyncThunk('typeConfig/safeTradeDict', async () => {
  const res: any = await commonDataApi.getIndustryList();
  const {
    code,
    data: { tradeDict },
  } = res;
  if (code === '200') {
    return tradeDict;
  }
});

// updateCommonData:any; CaseReducer<any, PayloadAction<any | undefined>>

export const commonDataSlice = createSlice<
  commonDataType,
  { updateTradeMap: CaseReducer<any, PayloadAction<any>> },
  'commonData'
>({
  name: 'commonData',
  initialState: {
    status: 'idle',
    industryList: [],
    error: null,
    tradeMap: new Map(),
  },
  reducers: {
    updateTradeMap: (state, action) => {
      console.log('--action---:', action);
    },
  },
  extraReducers(builder) {
    builder
      .addCase(getIndustryList.pending, (state, action) => {
        state.status = 'loading';
      })
      .addCase(getIndustryList.fulfilled, (state, action) => {
        state.status = 'succeeded';
        // console.log('--action---:', action);
        const tempIndustryList = action.payload;
        state.industryList = tempIndustryList;
        // action.dispatch(commonDataSlice.actions.updateTradeMap(action.payload)); // 没有dispatch属性
        const tempTradeMap: Map<string, string> = new Map();
        tempIndustryList.forEach((item: any) => {
          const { tradeDictName, tradeDictCode } = item;
          tempTradeMap.set(tradeDictCode, tradeDictName);
        });
        state.tradeMap = tempTradeMap;
      })
      .addCase(getIndustryList.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message || '获取getIndustryList报错';
      });
  },
});
